import {useDrop} from "react-dnd";
import {useComponentConfigStore} from "../../stores/component-config.tsx";
import {getComponentById, useComponentsStore} from "../../stores/components.tsx";

export interface ItemType {
    type: string;
    dragType?: 'move' | 'add',
    id: number
}

export function useMateRailDrop(accept: string[], id: number) {
    const {addComponent, components, deleteComponent} = useComponentsStore();
    const {componentConfig} = useComponentConfigStore();
    // 放置源
    const [{canDrop}, drop] = useDrop(() => ({
        // accept 指定接收的 type，
        accept,
        // 当拖拽元素进入目标元素时，会触发drop函数
        drop: (item: ItemType, monitor) => {
            // 判断是否已经拖拽过
            const didDrop = monitor.didDrop()
            if (didDrop || item.id === id) {
                return;
            }
            // 判断移动的组件和目标组件是否都是Form容器
            //  const tagetComponentType = getComponentById(id, components)


            if (item.dragType === 'move') {
                // 判断移动的组件是否存在
                const component = getComponentById(item.id, components)
                if (!component) return;
                // 判断是否是父组件拖动进子组件，如果是 直接返回不作处理
                const isParent = getComponentById(id, components)
                if (isParent) return;

                deleteComponent(item.id)
                addComponent(component, id)
                return;
            }

            const ids = new Date().getTime()
            const props = componentConfig[item.type].defaultProps;
            addComponent({
                id:ids,
                name: item.type,
                props:{
                    ...props,
                    name:item.type +"_" + ids.toString().slice(ids.toString().length-5,ids.toString().length),

                },
                styles: componentConfig[item.type].styles,
                parentId: id,
                desc: componentConfig[item.type].desc,

            }, id)
        },
        collect: (monitor) => ({
            canDrop: monitor.canDrop(),
        }),
    }));

    return {canDrop, drop}
}